﻿using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using tomenglertde.SetupProject.Model;

namespace tomenglertde.SetupProject.ViewModel
{
    public class SetupFile : SetupItem
    {
        public SetupFile(NodeEntity node, SetupProjectViewModel project) 
            : base(node, project)
        {
        }

        public string SourcePath
        {
            get
            {
                return Node.GetValue("SourcePath");
            }
        }

        public string TargetName
        {
            get
            {
                var name = Node.GetValue("TargetName");
                return string.IsNullOrEmpty(name) ? SourcePath : name;
            }
        }

        public override string Id
        {
            get
            {
                return Node.Name.Split(':')[1];
            }
            set
            {
                Node.Name = Node.Name.Split(':')[0] + ":" + value;
                Project.BeginSave();
            }
        }

        public bool IsDependency
        {
            get
            {
                return bool.Parse(Node.GetValue("IsDependency"));
            }
        }

        public bool Exclude
        {
            get
            {
                return bool.Parse(Node.GetValue("Exclude"));
            }
            set
            {
                Node.SetValue("Exclude", value.ToString(CultureInfo.InvariantCulture).ToUpperInvariant());
                Project.BeginSave();
            }
        }

        public IEnumerable<SetupProjectOutput> ProjectOutputs
        {
            get
            {
                return Project.ProjectOutputs.Where(p => OwnerIds.Contains(p.Id));
            }
        }

        public IEnumerable<object> Owners
        {
            get
            {
                return OwnerIds.Select(id => (object)Project.ProjectOutputs.FirstOrDefault(item => item.Id == id) ?? (object)Project.Files.FirstOrDefault(item => item.Id == id) ?? id);
            }
        }

        public IEnumerable<object> Children
        {
            get
            {
                return ChildIds.Select(id => (object)Project.Files.FirstOrDefault(item => item.Id == id) ?? id);
            }
        }
    }
}
